package com.hyjiacan.apps.audionly.data.repository

import android.os.Environment
import com.hyjiacan.apps.audionly.data.model.VideoFile
import java.io.File
import java.util.UUID

/**
 * FileRepository接口的实现类
 */
class FileRepositoryImpl : FileRepository {
    private val videoExtensions = setOf("mp4", "mkv", "avi", "mov", "wmv")

    override suspend fun getVideoFiles(directory: String): List<VideoFile> {
        val file = File(directory)
        if (!file.exists() || !file.isDirectory) {
            return emptyList()
        }

        return file.listFiles()?.filter { it.isFile && isVideoFile(it) }?.map {
            VideoFile(
                id = UUID.randomUUID().toString(),
                name = it.name,
                path = it.absolutePath,
                duration = getVideoDuration(it.absolutePath),
                size = it.length(),
                format = getFileExtension(it.name)
            )
        } ?: emptyList()
    }

    override fun getRootDirectory(): String {
        return Environment.getExternalStorageDirectory().absolutePath
    }

    override fun fileExists(path: String): Boolean {
        return File(path).exists()
    }

    private fun isVideoFile(file: File): Boolean {
        val extension = getFileExtension(file.name).lowercase()
        return videoExtensions.contains(extension)
    }

    private fun getFileExtension(filename: String): String {
        val lastDotIndex = filename.lastIndexOf('.')
        return if (lastDotIndex > 0) filename.substring(lastDotIndex + 1) else ""
    }

    private fun getVideoDuration(path: String): Long {
        // 实际应用中，这里会使用MediaMetadataRetriever等API获取视频时长
        // 为了简化示例，这里返回一个模拟值
        return 60000 // 1分钟
    }
}